package one.bugu.zookeeper.rpc.framework.service.zookeeper;

import one.bugu.zookeeper.rpc.framework.annotations.RpcService;
import one.bugu.zookeeper.rpc.framework.service.RpcServiceConfiguration;
import one.bugu.zookeeper.rpc.framework.service.socket.ServiceSocket;
import one.bugu.zookeeper.rpc.framework.util.SpringContextUtil;
import one.bugu.zookeeper.rpc.framework.zookeeper.ZooKeeperHelper;
import one.bugu.zookeeper.rpc.framework.zookeeper.ZookeeperConfiguration;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Created Date 2019/2/14
 * Time: 14:31
 * Description:
 */
public class RegisterCenterProviderImpl implements IRegisterCenterProvider {

    private ZookeeperConfiguration zookeeperConfiguration;
    private RpcServiceConfiguration rpcServiceConfiguration;

    private ZooKeeperHelper zooKeeperHelper;

    public static Map<String, Object> serverBean = new HashMap<>();

    private static Logger logger = LoggerFactory.getLogger(RegisterCenterProviderImpl.class);

    private Thread socketThread;

    public RegisterCenterProviderImpl(ZookeeperConfiguration zookeeperConfiguration, RpcServiceConfiguration rpcServiceConfiguration) {
        this.zookeeperConfiguration = zookeeperConfiguration;
        this.rpcServiceConfiguration = rpcServiceConfiguration;
    }

    @Override
    public void registerProvider(String serverName, List<String> ips) {
        if (zooKeeperHelper == null) {
            zooKeeperHelper = new ZooKeeperHelper(zookeeperConfiguration.getUrl(), new ServerNodeChangeWatcher());
        }
        String path = zookeeperConfiguration.getPath() + "/" + serverName;
        if (!zooKeeperHelper.existsNode(path)) {
            String resultPath = zooKeeperHelper.createNode(path, null);
            if (StringUtils.isEmpty(resultPath)) {
                logger.info("RPC服务注册失败,服务名：{}", serverName);
                return;
            }
        }
        for (String ip : ips) {
            String node = path + "/" + ip;
            if (!zooKeeperHelper.existsNode(node)) {
                String resultPath = zooKeeperHelper.createTempNode(node, null);
                if (StringUtils.isEmpty(resultPath)) {
                    logger.info("RPC服务注册失败,服务名：{}，IP地址：{}", serverName, ip);
                }
            }
        }
    }


    public void updateProvider() {
        Map<String, Object> beansWithAnnotation = SpringContextUtil.getApplicationContext().getBeansWithAnnotation(RpcService.class);
        if (beansWithAnnotation == null || beansWithAnnotation.isEmpty()) {
            return;
        }
        //Socket地址
        serverBean.clear();
        List<String> ips = getIp();
        for (String key : beansWithAnnotation.keySet()) {
            String serverName = beansWithAnnotation.get(key).getClass().getAnnotation(RpcService.class).name();
            serverBean.put(serverName, beansWithAnnotation.get(key));
            registerProvider(serverName, ips);
        }
        if (socketThread == null) {
            socketThread = new Thread(new ServiceSocket(rpcServiceConfiguration));
        }
        if (!socketThread.isAlive()) {
            socketThread.start();
        }
    }


    /**
     * 获取IP
     *
     * @return IP地址：端口号
     */
    public List<String> getIp() {
        List<String> host_ip_list = new ArrayList<String>();
        try {
            for (NetworkInterface networkInterface : Collections
                    .list(NetworkInterface.getNetworkInterfaces())) {
                for (InetAddress addr : Collections.list(networkInterface.getInetAddresses())) {
                    if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && addr.isSiteLocalAddress()) {
                        host_ip_list.add(addr.getHostAddress() + ":" + rpcServiceConfiguration.getPort());
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("获取IP地址异常", e);
        }
        return host_ip_list;

    }

    class ServerNodeChangeWatcher implements Watcher {

        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                logger.info("Watch received SyncConnected event");
                updateProvider();
            }
            if (event.getState() == Event.KeeperState.Disconnected) {
                logger.info("Watch received Disconnected event");
                zooKeeperHelper = null;
            }
        }
    }


}
